package com.recipedb.recipedb.service.impl;

import com.recipedb.recipedb.entity.UserFollow;
import com.recipedb.recipedb.entity.UserFollowId;
import com.recipedb.recipedb.entity.Recipe;
import com.recipedb.recipedb.repository.UserFollowRepository;
import com.recipedb.recipedb.repository.RecipeRepository;
import com.recipedb.recipedb.service.UserFollowService;
import com.recipedb.recipedb.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class UserFollowServiceImpl implements UserFollowService {

    @Autowired
    private UserFollowRepository repository;

    @Autowired
    private RecipeRepository recipeRepository;

    @Autowired
    private UserService userService;

    // 基本 CRUD 操作
    @Override
    public UserFollow save(UserFollow entity) {
        return repository.save(entity);
    }

    @Override
    public void deleteById(UserFollowId id) {  // 修改参数类型
        repository.deleteById(id);
    }

    @Override
    public Optional<UserFollow> findById(UserFollowId id) {  // 修改参数类型
        return repository.findById(id);
    }

    @Override
    public List<UserFollow> findAll() {
        return repository.findAll();
    }

    // 关注关系查询
    /*@Override
    public List<UserFollow> findByFollowerId(Long followerId) {
        return repository.findByFollowerId(followerId);
    }
*/
    @Override
    public List<UserFollow> findByFollowerId(Long followerId) {
        return repository.findByFollowerIdOrderByCreatedAtDesc(followerId);
    }



    /*@Override
    public List<UserFollow> findByFolloweeId(Long followeeId) {
        return repository.findByFolloweeId(followeeId);
    }*/

    @Override
    public List<UserFollow> findByFolloweeId(Long followeeId) {
        // 此时会自动调用上面新增的 findByFolloweeIdOrderByCreatedAtDesc 方法
        return repository.findByFolloweeIdOrderByCreatedAtDesc(followeeId);
    }


    // 核心功能：获取关注的用户发布的菜谱
    @Override
    public List<Recipe> getFollowedUsersRecipes(Long followerId) {
        // 1. 获取用户关注的所有用户ID
        List<Long> followedUserIds = getFollowedUserIds(followerId);

        // 2. 如果没有关注任何人，返回空列表
        if (followedUserIds.isEmpty()) {
            return List.of();
        }

        // 3. 查询这些用户发布的所有菜谱，按创建时间倒序排列
        return recipeRepository.findByUserIdInOrderByCreatedAtDesc(followedUserIds);
    }

    // 关注用户
    @Override
    @Transactional
    public boolean followUser(Long followerId, Long followeeId) {
        // 不能关注自己
        if (followerId.equals(followeeId)) {
            throw new RuntimeException("不能关注自己");
        }

        // 验证用户是否存在
        userService.findById(followerId)
                .orElseThrow(() -> new RuntimeException("关注者用户不存在"));
        userService.findById(followeeId)
                .orElseThrow(() -> new RuntimeException("被关注者用户不存在"));

        // 检查是否已关注
        if (isFollowing(followerId, followeeId)) {
            throw new RuntimeException("已关注该用户");
        }

        // 创建关注记录
        UserFollow userFollow = new UserFollow();
        userFollow.setFollowerId(followerId);
        userFollow.setFolloweeId(followeeId);
        userFollow.setCreatedAt(LocalDateTime.now());

        repository.save(userFollow);

        // 更新用户统计信息
        userService.incrementFollowCount(followerId);
        userService.incrementFanCount(followeeId);

        return true;
    }

    // 取消关注
    @Override
    @Transactional
    public boolean unfollowUser(Long followerId, Long followeeId) {
        // 检查关注关系是否存在
        if (!isFollowing(followerId, followeeId)) {
            throw new RuntimeException("未关注该用户");
        }

        // 删除关注记录
        boolean deleted = deleteByFollowerIdAndFolloweeId(followerId, followeeId);

        if (deleted) {
            // 更新用户统计信息
            userService.decrementFollowCount(followerId);
            userService.decrementFanCount(followeeId);
        }

        return deleted;
    }

    // 检查是否已关注
    @Override
    public boolean isFollowing(Long followerId, Long followeeId) {
        return repository.existsByFollowerIdAndFolloweeId(followerId, followeeId);
    }

    // 获取用户关注的所有用户ID
    @Override
    public List<Long> getFollowedUserIds(Long followerId) {
        return repository.findFolloweeIdsByFollowerId(followerId);
    }

    // 获取用户的所有粉丝ID
    @Override
    public List<Long> getFollowerIds(Long followeeId) {
        return repository.findFollowerIdsByFolloweeId(followeeId);
    }

    // 统计关注数量
    @Override
    public long getFollowCount(Long userId) {
        return repository.countByFollowerId(userId);
    }

    // 统计粉丝数量
    @Override
    public long getFollowerCount(Long userId) {
        return repository.countByFolloweeId(userId);
    }

    // 直接删除关注关系
    @Override
    @Transactional
    public boolean deleteByFollowerIdAndFolloweeId(Long followerId, Long followeeId) {
        int deletedCount = repository.deleteByFollowerIdAndFolloweeId(followerId, followeeId);
        return deletedCount > 0;
    }
}